# -*- coding: utf-8 -*-
from datetime import datetime
from random import randint
import re

from flask import abort, jsonify
from flask import current_app
from flask import make_response
from flask import request
from flask import session

from info import redis_store, db
from info.constants import IMAGE_CODE_REDIS_EXPIRES, SMS_CODE_REDIS_EXPIRES
from info.libs.yuntongxun.sms import CCP
from info.models import User
from info.utills.captcha.response_code import RET
from . import passport_blue
from info.utills.captcha.captcha import captcha


@passport_blue.route('/logout')
def logout():
    session.pop('user_id', None)
    session.pop('mobile', None)
    session.pop('nick_name', None)
    session.pop('is_admin', None)
    return jsonify(errno=RET.OK, errmsg="退出成功")


@passport_blue.route('/login', methods=['post', 'get'])
def login():
    """登陆"""
    # 1.获取数据mobile,password
    data_dict = request.json
    mobile = data_dict.get('mobile')
    password = data_dict.get('password')
    # 2.校验参数
    if not all([mobile, password]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")
    # 3.正则验证手机号是否合法
    result = re.match(r'^1[3-9]\d{9}$', mobile)
    if not result:
        return jsonify(errno=RET.PARAMERR, errmsg="手机号格式不正确")
    # 4.判断该手机号是否注册
    try:
        user = User.query.filter_by(mobile=mobile).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库查询失败")
    if not user:
        return jsonify(errno=RET.USERERR, errmsg="手机号未注册")
    # 5.判断密码是否正确
    if not user.check_password(password):
        return jsonify(errno=RET.PWDERR, errmsg="密码错误")
    # 6.保存用户的登陆状态
    session['user_id'] = user.id
    session['mobile'] = user.mobile
    session['nick_name'] = user.nick_name
    # 7.设置当前用户最后一次登录的时间
    user.last_login = datetime.now()
    # db.session.commit()这个commit操作交由我们配置后的钩子函数去执行
    return jsonify(errno=RET.OK, errmsg="登陆成功")


@passport_blue.route('/register', methods=['post', 'get'])
def register():
    """注册"""
    # 1.获取数据mobile，smscode，password，参数errno
    data_dict = request.json
    mobile = data_dict.get('mobile')
    smscode = data_dict.get('smscode')
    password = data_dict.get('password')
    # 2.校验参数
    if not all([mobile, smscode, password]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")
    # 3.正则验证手机号是否合法
    result = re.match(r'^1[3-9]\d{9}$', mobile)
    if not result:
        return jsonify(errno=RET.PARAMERR, errmsg="手机号格式不正确")
    # 4.从redis中取到真实的短信验证码
    try:
        real_smscold = redis_store.get('SMS_' + mobile)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询失败")
    if not real_smscold:
        return jsonify(errno=RET.NODATA, errmsg="短信验证码已失效")
        # 5.内容比对，不一致返回验证码输入错误
    if real_smscold != smscode:
        return jsonify(errno=RET.DATAERR, errmsg="短信验证码错误")
    # 5.如果一致，则注册逻辑
    user = User()
    user.mobile = mobile
    user.nick_name = mobile
    # 会调用 @password.setter装饰器，对密码进行加密处理
    user.password = password
    # 记录用户最后一次登陆时间
    user.last_login = datetime.now()
    # 6.添加到数据库
    try:
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据保存失败")
    # 7.session 中保存数据，表示当前用户已经登陆
    session['user_id'] = user.id
    session['mobile'] = user.mobile
    session['nick_name'] = user.nick_name
    # 8.返回响应
    return jsonify(errno=RET.OK, errmsg="注册成功")


@passport_blue.route('/msg_cold', methods=['post', 'get'])
def msg_cold():
    """发送短信验证码"""
    # 1.接收数据：手机号mobile,验证码编号image_code_id，用户输入的验证码内容image_code
    data_dict = request.json
    mobile = data_dict.get('mobile')
    image_code_id = data_dict.get('image_code_id')
    image_code = data_dict.get('image_code')

    # 2.判断数据是否为空
    if not all([mobile, image_code_id, image_code]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

    # 3.正则验证手机号是否合法
    result = re.match(r'^1[3-9]\d{9}$', mobile)
    if not result:
        return jsonify(errno=RET.PARAMERR, errmsg="手机号格式不正确")
    # 3.1验证该手机号是否已经注册过
    try:
        user = User.query.filter_by(mobile=mobile).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库查询失败")
    if user:
        return jsonify(errno=RET.DATAEXIST, errmsg="手机号已注册")
    # 4.从redis中取到真实的验证码
    try:
        real_code = redis_store.get('imageCold' + image_code_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库查询失败")
    if not real_code:
        return jsonify(errno=RET.NODATA, errmsg="验证码已失效")
    # 5.内容比对，不一致返回验证码输入错误
    if real_code.upper() != image_code.upper():
        return jsonify(errno=RET.DATAERR, errmsg="验证码错误")
    # 6.生成随机短信内容
    num = randint(1000, 9999)
    current_app.logger.info(num)
    # # 7.调用工具发送短信
    # ccp = CCP()
    # res = ccp.send_template_sms(mobile, ['%s' % num, SMS_CODE_REDIS_EXPIRES // 60], 1)
    # # bug{'statusMsg': '【账号】主账户绑定的测试号码个数为零', 'statusCode': '111188'}
    # if res != 0:
    #     return jsonify(errno=RET.THIRDERR, errmsg="短信发送失败")
    # 8.保存短信内容到redis'
    try:
        redis_store.set('SMS_' + mobile, num, SMS_CODE_REDIS_EXPIRES)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据保存失败")
    # 9.告知用户短信发送成功
    return jsonify(errno=RET.OK, errmsg="发送成功", num='短信验证码是：'+str(num))


@passport_blue.route('/image_code')
def image_code():
    """返回图片验证码"""
    imageColdId = request.args.get('imageCode')
    if not imageColdId:
        return abort(403)
        # 生成图片验证码
    try:
        name, text, img = captcha.generate_captcha()
        #   保存文字信息到redis，
        redis_store.set('imageCold' + imageColdId, text, IMAGE_CODE_REDIS_EXPIRES)
        response = make_response(img)
        response.mime = 'image/jpg'
        return response
    except Exception as e:
        current_app.logger.error(e)
        abort(500)
        # 将图片返回给浏览器
